from django.db import connection,transaction
from django.http import HttpResponse
from mvc.models import *
from django.utils import simplejson as json
from mvc import trans,langs
import resources
import traceback

@transaction.commit_manually
def deploy(request):
    try:
        cursor = connection.cursor()
        
        
        
        clearAllCards(cursor)
        deployAllCards(cursor)
        clearAllMaps(cursor)
        deployAllMaps(cursor)
        clearAllCampaigns(cursor)
        deployAllCampaigns(cursor)
        clearAllBattle_points(cursor)
        deployAllBattle_points(cursor)
        clearAllLevel_props(cursor)
        deployAllLevel_props(cursor)
        clearAllNpcs(cursor)
        deployAllNpcs(cursor)
        clearAllNpc_units(cursor)
        deployAllNpc_units(cursor)
        clearAllShop_items(cursor)
        deployAllShop_items(cursor)
        clearAllTaverns(cursor)
        deployAllTaverns(cursor)        
        clearAllVersus_battle_points(cursor)
        deployAllVersus_battle_points(cursor)
        clearAllConstantss(cursor)
        deployAllConstantss(cursor)
        clearAllForge_item_datas(cursor)
        deployAllForge_item_datas(cursor)
        clearAllItem_fragments(cursor)
        deployAllItem_fragments(cursor)
        clearAllItem_extra_props(cursor)
        deployAllItem_extra_props(cursor)
        clearAllItem_perfect_prop_datas(cursor)
        deployAllItem_perfect_prop_datas(cursor)
        
        clearAllOpen_bags(cursor)
        deployAllOpen_bags(cursor)        
        clearAllSilver_bags(cursor)
        deployAllSilver_bags(cursor)
        clearAllGift_bags(cursor)
        deployAllGift_bags(cursor)
        clearAllTreasures(cursor)
        deployAllTreasures(cursor)                
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')



def deployItemAction(request):
    try:
        cursor = connection.cursor()
        clearAllItems(cursor)
        deployAllItems(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllItems_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Item,))
    if count > 0 :
        ids = cursor.fetchall()
        for itemId in ids :
            removeLanguage(cursor,itemId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Item,))

def clearAllItems(cursor):
    sql = """ select deployId from mvc_item """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllItems(cursor):
    items = Item.objects.all()
    for item in items:
        gameId = deployItem(cursor,item)
        deployLanguage(cursor,item.name,gameId,item.deployId)
        deployLanguage(cursor,item.desc,gameId,item.deployId)
        resources.deployResource(cursor,item.deployId,ModelTypes.Type_Item,item.itemres)
        

def deployItem(cursor,item):
    langeditem = Item()
    langeditem.id = item.id
    langeditem.deployId = item.deployId
    langednamex = 'item'
    lang = langs.getlangById(item.name)
    if lang:
        langeditem.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(item.desc)
    if lang:
        langeditem.desc = lang.value
                
    langeditem.categoryId = item.categoryId
    langeditem.typeId = item.typeId
    langeditem.attackType = item.attackType
    langeditem.level = item.level
    langeditem.qualityId = item.qualityId
    langeditem.enchantTime = item.enchantTime
    langeditem.bindType = item.bindType
    langeditem.props = item.props
    langeditem.propertySet = item.propertySet
    langeditem.requiredLevel = item.requiredLevel
    langeditem.requiredCareerId = item.requiredCareerId
    langeditem.requiredGenderId = item.requiredGenderId
    langeditem.unique = item.unique
    langeditem.maxStack = item.maxStack
    langeditem.recyclingPrice = item.recyclingPrice
    langeditem.canSell = item.canSell
    langeditem.skillId = item.skillId
    langeditem.itemres = item.itemres
    
    itemJson = trans.item2StoreJson(langeditem)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(itemJson,ensure_ascii=False)
    print "Item",item.deployId,finalJson
    cursor.execute(sql,(item.deployId,ModelTypes.Type_Item,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deploySkillAction(request):
    try:
        cursor = connection.cursor()
        clearAllSkills(cursor)
        deployAllSkills(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllSkills_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Skill,))
    if count > 0 :
        ids = cursor.fetchall()
        for skillId in ids :
            removeLanguage(cursor,skillId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Skill,))

def clearAllSkills(cursor):
    sql = """ select deployId from mvc_skill """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllSkills(cursor):
    skills = Skill.objects.all()
    for skill in skills:
        gameId = deploySkill(cursor,skill)
        deployLanguage(cursor,skill.name,gameId,skill.deployId)
        deployLanguage(cursor,skill.desc,gameId,skill.deployId)
        resources.deployResource(cursor,skill.deployId,ModelTypes.Type_Skill,skill.skillres)
        

def deploySkill(cursor,skill):
    langedskill = Skill()
    langedskill.id = skill.id
    langedskill.deployId = skill.deployId
    langednamex = 'skill'
    lang = langs.getlangById(skill.name)
    if lang:
        langedskill.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(skill.desc)
    if lang:
        langedskill.desc = lang.value
                
    langedskill.category = skill.category
    langedskill.targetType = skill.targetType
    langedskill.damage = skill.damage
    langedskill.triggerDamage = skill.triggerDamage
    langedskill.status = skill.status
    langedskill.triggerStatus = skill.triggerStatus
    langedskill.trigger = skill.trigger
    langedskill.property = skill.property
    langedskill.changeFury = skill.changeFury
    langedskill.sound = skill.sound
    langedskill.skillres = skill.skillres
    
    skillJson = trans.skill2StoreJson(langedskill)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(skillJson,ensure_ascii=False)
    print "Skill",skill.deployId,finalJson
    cursor.execute(sql,(skill.deployId,ModelTypes.Type_Skill,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployTaskAction(request):
    try:
        cursor = connection.cursor()
        clearAllTasks(cursor)
        deployAllTasks(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllTasks_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Task,))
    if count > 0 :
        ids = cursor.fetchall()
        for taskId in ids :
            removeLanguage(cursor,taskId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Task,))

def clearAllTasks(cursor):
    sql = """ select deployId from mvc_task """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllTasks(cursor):
    tasks = Task.objects.all()
    for task in tasks:
        gameId = deployTask(cursor,task)
        deployLanguage(cursor,task.name,gameId,task.deployId)
        deployLanguage(cursor,task.desc,gameId,task.deployId)
        

def deployTask(cursor,task):
    langedtask = Task()
    langedtask.id = task.id
    langedtask.deployId = task.deployId
    langednamex = 'task'
    lang = langs.getlangById(task.name)
    if lang:
        langedtask.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(task.desc)
    if lang:
        langedtask.desc = lang.value
                
    langedtask.level = task.level
    langedtask.catalog = task.catalog
    langedtask.type = task.type
    langedtask.dests = task.dests
    langedtask.compaignId = task.compaignId
    langedtask.postTaskId = task.postTaskId
    langedtask.startTalk = task.startTalk
    langedtask.endTalk = task.endTalk
    langedtask.deduct = task.deduct
    langedtask.reward = task.reward
    
    taskJson = trans.task2StoreJson(langedtask)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(taskJson,ensure_ascii=False)
    print "Task",task.deployId,finalJson
    cursor.execute(sql,(task.deployId,ModelTypes.Type_Task,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployCardAction(request):
    try:
        cursor = connection.cursor()
        clearAllCards(cursor)
        deployAllCards(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllCards_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Card,))
    if count > 0 :
        ids = cursor.fetchall()
        for cardId in ids :
            removeLanguage(cursor,cardId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Card,))

def clearAllCards(cursor):
    sql = """ select deployId from mvc_card """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllCards(cursor):
    cards = Card.objects.all()
    for card in cards:
        gameId = deployCard(cursor,card)
        deployLanguage(cursor,card.name,gameId,card.deployId)
        deployLanguage(cursor,card.desc,gameId,card.deployId)
        resources.deployResource(cursor,card.deployId,ModelTypes.Type_Card,card.cardres)
        

def deployCard(cursor,card):
    langedcard = Card()
    langedcard.id = card.id
    langedcard.deployId = card.deployId
    langednamex = 'card'
    lang = langs.getlangById(card.name)
    if lang:
        langedcard.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(card.desc)
    if lang:
        langedcard.desc = lang.value
                
    langedcard.module = card.module
    langedcard.catalog = card.catalog
    langedcard.type = card.type
    langedcard.quality = card.quality
    langedcard.award = card.award
    langedcard.condition = card.condition
    langedcard.nextCardId = card.nextCardId
    langedcard.cardres = card.cardres
    
    cardJson = trans.card2StoreJson(langedcard)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(cardJson,ensure_ascii=False)
    print "Card",card.deployId,finalJson
    cursor.execute(sql,(card.deployId,ModelTypes.Type_Card,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployMapAction(request):
    try:
        cursor = connection.cursor()
        clearAllMaps(cursor)
        deployAllMaps(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllMaps_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Map,))
    if count > 0 :
        ids = cursor.fetchall()
        for mapId in ids :
            removeLanguage(cursor,mapId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Map,))

def clearAllMaps(cursor):
    sql = """ select deployId from mvc_map """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllMaps(cursor):
    maps = Map.objects.all()
    for map in maps:
        gameId = deployMap(cursor,map)
        deployLanguage(cursor,map.name,gameId,map.deployId)
        resources.deployResource(cursor,map.deployId,ModelTypes.Type_Map,map.mapres)
        

def deployMap(cursor,map):
    langedmap = Map()
    langedmap.id = map.id
    langedmap.deployId = map.deployId
    langednamex = 'map'
    lang = langs.getlangById(map.name)
    if lang:
        langedmap.name = lang.value
        langednamex = lang.value        
    langedmap.campaignIds = map.campaignIds
    langedmap.mapres = map.mapres
    
    mapJson = trans.map2StoreJson(langedmap)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(mapJson,ensure_ascii=False)
    print "Map",map.deployId,finalJson
    cursor.execute(sql,(map.deployId,ModelTypes.Type_Map,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployCampaignAction(request):
    try:
        cursor = connection.cursor()
        clearAllCampaigns(cursor)
        deployAllCampaigns(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllCampaigns_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Campaign,))
    if count > 0 :
        ids = cursor.fetchall()
        for campaignId in ids :
            removeLanguage(cursor,campaignId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Campaign,))

def clearAllCampaigns(cursor):
    sql = """ select deployId from mvc_campaign """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllCampaigns(cursor):
    campaigns = Campaign.objects.all()
    for campaign in campaigns:
        gameId = deployCampaign(cursor,campaign)
        deployLanguage(cursor,campaign.name,gameId,campaign.deployId)
        deployLanguage(cursor,campaign.desc,gameId,campaign.deployId)
        resources.deployResource(cursor,campaign.deployId,ModelTypes.Type_Campaign,campaign.music)
        

def deployCampaign(cursor,campaign):
    langedcampaign = Campaign()
    langedcampaign.id = campaign.id
    langedcampaign.deployId = campaign.deployId
    langednamex = 'campaign'
    lang = langs.getlangById(campaign.name)
    if lang:
        langedcampaign.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(campaign.desc)
    if lang:
        langedcampaign.desc = lang.value
                
    langedcampaign.battlePointIds = campaign.battlePointIds
    langedcampaign.status = campaign.status
    langedcampaign.vip = campaign.vip
    langedcampaign.mapId = campaign.mapId
    langedcampaign.userLevel = campaign.userLevel
    langedcampaign.coorX = campaign.coorX
    langedcampaign.coorY = campaign.coorY
    langedcampaign.music = campaign.music
    langedcampaign.frontCompaignIds = campaign.frontCompaignIds
    langedcampaign.afterCompaignIds = campaign.afterCompaignIds
    
    campaignJson = trans.campaign2StoreJson(langedcampaign)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(campaignJson,ensure_ascii=False)
    print "Campaign",campaign.deployId,finalJson
    cursor.execute(sql,(campaign.deployId,ModelTypes.Type_Campaign,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployBattle_pointAction(request):
    try:
        cursor = connection.cursor()
        clearAllBattle_points(cursor)
        deployAllBattle_points(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllBattle_points_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Battle_point,))
    if count > 0 :
        ids = cursor.fetchall()
        for battle_pointId in ids :
            removeLanguage(cursor,battle_pointId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Battle_point,))

def clearAllBattle_points(cursor):
    sql = """ select deployId from mvc_battle_point """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllBattle_points(cursor):
    battle_points = Battle_point.objects.all()
    for battle_point in battle_points:
        gameId = deployBattle_point(cursor,battle_point)
        deployLanguage(cursor,battle_point.name,gameId,battle_point.deployId)
        deployLanguage(cursor,battle_point.desc,gameId,battle_point.deployId)
        

def deployBattle_point(cursor,battle_point):
    langedbattle_point = Battle_point()
    langedbattle_point.id = battle_point.id
    langedbattle_point.deployId = battle_point.deployId
    langednamex = 'battle_point'
    lang = langs.getlangById(battle_point.name)
    if lang:
        langedbattle_point.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(battle_point.desc)
    if lang:
        langedbattle_point.desc = lang.value
                
    langedbattle_point.npcId = battle_point.npcId
    langedbattle_point.campaignId = battle_point.campaignId
    langedbattle_point.weatherIds = battle_point.weatherIds
    langedbattle_point.roundMax = battle_point.roundMax
    langedbattle_point.leaderDead = battle_point.leaderDead
    langedbattle_point.roundLimit = battle_point.roundLimit
    langedbattle_point.leader = battle_point.leader
    langedbattle_point.round = battle_point.round
    langedbattle_point.endCondition = battle_point.endCondition
    langedbattle_point.attackerMax = battle_point.attackerMax
    langedbattle_point.defenderMax = battle_point.defenderMax
    langedbattle_point.areaId = battle_point.areaId
    langedbattle_point.drops = battle_point.drops
    langedbattle_point.energyCost = battle_point.energyCost
    langedbattle_point.passCount = battle_point.passCount
    langedbattle_point.difficulty = battle_point.difficulty
    langedbattle_point.starMax = battle_point.starMax
    langedbattle_point.frontBattlePointIds = battle_point.frontBattlePointIds
    langedbattle_point.afterBattlePointIds = battle_point.afterBattlePointIds
    
    battle_pointJson = trans.battle_point2StoreJson(langedbattle_point)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(battle_pointJson,ensure_ascii=False)
    print "Battle_point",battle_point.deployId,finalJson
    cursor.execute(sql,(battle_point.deployId,ModelTypes.Type_Battle_point,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployLevel_propAction(request):
    try:
        cursor = connection.cursor()
        clearAllLevel_props(cursor)
        deployAllLevel_props(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllLevel_props_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Level_prop,))
    if count > 0 :
        ids = cursor.fetchall()
        for level_propId in ids :
            removeLanguage(cursor,level_propId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Level_prop,))

def clearAllLevel_props(cursor):
    sql = """ select deployId from mvc_level_prop """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllLevel_props(cursor):
    level_props = Level_prop.objects.all()
    for level_prop in level_props:
        gameId = deployLevel_prop(cursor,level_prop)
        

def deployLevel_prop(cursor,level_prop):
    langedlevel_prop = Level_prop()
    langedlevel_prop.id = level_prop.id
    langedlevel_prop.deployId = level_prop.deployId
    langednamex = 'level_prop'
    langedlevel_prop.exp = level_prop.exp
    langedlevel_prop.energyMax = level_prop.energyMax
    langedlevel_prop.battleCount = level_prop.battleCount
    langedlevel_prop.employeeCount = level_prop.employeeCount
    langedlevel_prop.skillCount = level_prop.skillCount
    langedlevel_prop.hp = level_prop.hp
    langedlevel_prop.physicalatk = level_prop.physicalatk
    langedlevel_prop.physicaldef = level_prop.physicaldef
    langedlevel_prop.magicatk = level_prop.magicatk
    langedlevel_prop.magicdef = level_prop.magicdef
    langedlevel_prop.award = level_prop.award
    langedlevel_prop.logos = level_prop.logos
    
    level_propJson = trans.level_prop2StoreJson(langedlevel_prop)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(level_propJson,ensure_ascii=False)
    print "Level_prop",level_prop.deployId,finalJson
    cursor.execute(sql,(level_prop.deployId,ModelTypes.Type_Level_prop,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployNpcAction(request):
    try:
        cursor = connection.cursor()
        clearAllNpcs(cursor)
        deployAllNpcs(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllNpcs_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Npc,))
    if count > 0 :
        ids = cursor.fetchall()
        for npcId in ids :
            removeLanguage(cursor,npcId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Npc,))

def clearAllNpcs(cursor):
    sql = """ select deployId from mvc_npc """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllNpcs(cursor):
    npcs = Npc.objects.all()
    for npc in npcs:
        gameId = deployNpc(cursor,npc)
        deployLanguage(cursor,npc.name,gameId,npc.deployId)
        deployLanguage(cursor,npc.desc,gameId,npc.deployId)
        resources.deployResource(cursor,npc.deployId,ModelTypes.Type_Npc,npc.npcres)
        

def deployNpc(cursor,npc):
    langednpc = Npc()
    langednpc.id = npc.id
    langednpc.deployId = npc.deployId
    langednamex = 'npc'
    lang = langs.getlangById(npc.name)
    if lang:
        langednpc.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(npc.desc)
    if lang:
        langednpc.desc = lang.value
                
    langednpc.npcUnitIds = npc.npcUnitIds
    langednpc.npcres = npc.npcres
    
    npcJson = trans.npc2StoreJson(langednpc)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(npcJson,ensure_ascii=False)
    print "Npc",npc.deployId,finalJson
    cursor.execute(sql,(npc.deployId,ModelTypes.Type_Npc,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployNpc_unitAction(request):
    try:
        cursor = connection.cursor()
        clearAllNpc_units(cursor)
        deployAllNpc_units(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllNpc_units_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Npc_unit,))
    if count > 0 :
        ids = cursor.fetchall()
        for npc_unitId in ids :
            removeLanguage(cursor,npc_unitId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Npc_unit,))

def clearAllNpc_units(cursor):
    sql = """ select deployId from mvc_npc_unit """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllNpc_units(cursor):
    npc_units = Npc_unit.objects.all()
    for npc_unit in npc_units:
        gameId = deployNpc_unit(cursor,npc_unit)
        deployLanguage(cursor,npc_unit.name,gameId,npc_unit.deployId)
        deployLanguage(cursor,npc_unit.desc,gameId,npc_unit.deployId)
        resources.deployResource(cursor,npc_unit.deployId,ModelTypes.Type_Npc_unit,npc_unit.npcunitres)
        

def deployNpc_unit(cursor,npc_unit):
    langednpc_unit = Npc_unit()
    langednpc_unit.id = npc_unit.id
    langednpc_unit.deployId = npc_unit.deployId
    langednamex = 'npc_unit'
    lang = langs.getlangById(npc_unit.name)
    if lang:
        langednpc_unit.name = lang.value
        langednamex = lang.value        
    lang = langs.getlangById(npc_unit.desc)
    if lang:
        langednpc_unit.desc = lang.value
                
    langednpc_unit.level = npc_unit.level
    langednpc_unit.career = npc_unit.career
    langednpc_unit.gender = npc_unit.gender
    langednpc_unit.npcId = npc_unit.npcId
    langednpc_unit.idx = npc_unit.idx
    langednpc_unit.pos = npc_unit.pos
    langednpc_unit.hp = npc_unit.hp
    langednpc_unit.attackId = npc_unit.attackId
    langednpc_unit.physicalatk = npc_unit.physicalatk
    langednpc_unit.physicaldef = npc_unit.physicaldef
    langednpc_unit.magicatk = npc_unit.magicatk
    langednpc_unit.magicdef = npc_unit.magicdef
    langednpc_unit.furyAttackRate = npc_unit.furyAttackRate
    langednpc_unit.hardAttackRate = npc_unit.hardAttackRate
    langednpc_unit.hurtIncValue = npc_unit.hurtIncValue
    langednpc_unit.hurtDecValue = npc_unit.hurtDecValue
    langednpc_unit.hurtIncPercent = npc_unit.hurtIncPercent
    langednpc_unit.hurtDecPercent = npc_unit.hurtDecPercent
    langednpc_unit.skills = npc_unit.skills
    langednpc_unit.equipment = npc_unit.equipment
    langednpc_unit.style = npc_unit.style
    langednpc_unit.npcunitres = npc_unit.npcunitres
    
    npc_unitJson = trans.npc_unit2StoreJson(langednpc_unit)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(npc_unitJson,ensure_ascii=False)
    print "Npc_unit",npc_unit.deployId,finalJson
    cursor.execute(sql,(npc_unit.deployId,ModelTypes.Type_Npc_unit,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployShop_itemAction(request):
    try:
        cursor = connection.cursor()
        clearAllShop_items(cursor)
        deployAllShop_items(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllShop_items_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Shop_item,))
    if count > 0 :
        ids = cursor.fetchall()
        for shop_itemId in ids :
            removeLanguage(cursor,shop_itemId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Shop_item,))

def clearAllShop_items(cursor):
    sql = """ select deployId from mvc_shop_item """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllShop_items(cursor):
    shop_items = Shop_item.objects.all()
    for shop_item in shop_items:
        gameId = deployShop_item(cursor,shop_item)
        resources.deployResource(cursor,shop_item.deployId,ModelTypes.Type_Shop_item,shop_item.shop_itemres)
        

def deployShop_item(cursor,shop_item):
    langedshop_item = Shop_item()
    langedshop_item.id = shop_item.id
    langedshop_item.deployId = shop_item.deployId
    langednamex = 'shop_item'
    langedshop_item.tabId = shop_item.tabId
    langedshop_item.itemId = shop_item.itemId
    langedshop_item.coinPrice = shop_item.coinPrice
    langedshop_item.silverPrice = shop_item.silverPrice
    langedshop_item.status = shop_item.status
    langedshop_item.isDiscount = shop_item.isDiscount
    langedshop_item.coinPirceDiscount = shop_item.coinPirceDiscount
    langedshop_item.silverPriceDiscount = shop_item.silverPriceDiscount
    langedshop_item.levelLimit = shop_item.levelLimit
    langedshop_item.vipLevelLimit = shop_item.vipLevelLimit
    langedshop_item.rank = shop_item.rank
    langedshop_item.shop_itemres = shop_item.shop_itemres
    
    shop_itemJson = trans.shop_item2StoreJson(langedshop_item)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(shop_itemJson,ensure_ascii=False)
    print "Shop_item",shop_item.deployId,finalJson
    cursor.execute(sql,(shop_item.deployId,ModelTypes.Type_Shop_item,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployTavernAction(request):
    try:
        cursor = connection.cursor()
        clearAllTaverns(cursor)
        deployAllTaverns(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllTaverns_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Tavern,))
    if count > 0 :
        ids = cursor.fetchall()
        for tavernId in ids :
            removeLanguage(cursor,tavernId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Tavern,))

def clearAllTaverns(cursor):
    sql = """ select deployId from mvc_tavern """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllTaverns(cursor):
    taverns = Tavern.objects.all()
    for tavern in taverns:
        gameId = deployTavern(cursor,tavern)
        

def deployTavern(cursor,tavern):
    langedtavern = Tavern()
    langedtavern.id = tavern.id
    langedtavern.deployId = tavern.deployId
    langednamex = 'tavern'
    langedtavern.level = tavern.level
    langedtavern.requiredLevel = tavern.requiredLevel
    langedtavern.moneyType = tavern.moneyType
    langedtavern.money = tavern.money
    langedtavern.npcRates = tavern.npcRates
    langedtavern.taskRates = tavern.taskRates
    
    tavernJson = trans.tavern2StoreJson(langedtavern)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(tavernJson,ensure_ascii=False)
    print "Tavern",tavern.deployId,finalJson
    cursor.execute(sql,(tavern.deployId,ModelTypes.Type_Tavern,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployVersus_battle_pointAction(request):
    try:
        cursor = connection.cursor()
        clearAllVersus_battle_points(cursor)
        deployAllVersus_battle_points(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllVersus_battle_points_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Versus_battle_point,))
    if count > 0 :
        ids = cursor.fetchall()
        for versus_battle_pointId in ids :
            removeLanguage(cursor,versus_battle_pointId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Versus_battle_point,))

def clearAllVersus_battle_points(cursor):
    sql = """ select deployId from mvc_versus_battle_point """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllVersus_battle_points(cursor):
    versus_battle_points = Versus_battle_point.objects.all()
    for versus_battle_point in versus_battle_points:
        gameId = deployVersus_battle_point(cursor,versus_battle_point)
        

def deployVersus_battle_point(cursor,versus_battle_point):
    langedversus_battle_point = Versus_battle_point()
    langedversus_battle_point.id = versus_battle_point.id
    langedversus_battle_point.deployId = versus_battle_point.deployId
    langednamex = 'versus_battle_point'
    langedversus_battle_point.level = versus_battle_point.level
    langedversus_battle_point.battlePointId = versus_battle_point.battlePointId
    
    versus_battle_pointJson = trans.versus_battle_point2StoreJson(langedversus_battle_point)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(versus_battle_pointJson,ensure_ascii=False)
    print "Versus_battle_point",versus_battle_point.deployId,finalJson
    cursor.execute(sql,(versus_battle_point.deployId,ModelTypes.Type_Versus_battle_point,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployConstantsAction(request):
    try:
        cursor = connection.cursor()
        clearAllConstantss(cursor)
        deployAllConstantss(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllConstantss_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Constants,))
    if count > 0 :
        ids = cursor.fetchall()
        for constantsId in ids :
            removeLanguage(cursor,constantsId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Constants,))

def clearAllConstantss(cursor):
    sql = """ select deployId from mvc_constants """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllConstantss(cursor):
    constantss = Constants.objects.all()
    for constants in constantss:
        gameId = deployConstants(cursor,constants)
        

def deployConstants(cursor,constants):
    langedconstants = Constants()
    langedconstants.id = constants.id
    langedconstants.deployId = constants.deployId
    langednamex = 'constants'
    langedconstants.energeBoostPeriod = constants.energeBoostPeriod
    langedconstants.energeBoostUnit = constants.energeBoostUnit
    langedconstants.practiceDuration1 = constants.practiceDuration1
    langedconstants.practiceDuration2 = constants.practiceDuration2
    langedconstants.practiceDuration3 = constants.practiceDuration3
    langedconstants.practiceSpeedExtraExp = constants.practiceSpeedExtraExp
    langedconstants.practiceCostCoeff1 = constants.practiceCostCoeff1
    langedconstants.practiceCostCoeff2 = constants.practiceCostCoeff2
    langedconstants.practiceCostCoeff3 = constants.practiceCostCoeff3
    langedconstants.practiceSpeedCost = constants.practiceSpeedCost
    langedconstants.practiceDirectlyFinishCost = constants.practiceDirectlyFinishCost
    langedconstants.practiceExpUnitCoeff1 = constants.practiceExpUnitCoeff1
    langedconstants.practiceExpUnitCoeff2 = constants.practiceExpUnitCoeff2
    langedconstants.practiceExpUnitCoeff3 = constants.practiceExpUnitCoeff3
    langedconstants.practiceSpeedItemId = constants.practiceSpeedItemId
    langedconstants.versusItemId = constants.versusItemId
    langedconstants.versusLevelLimit = constants.versusLevelLimit
    
    constantsJson = trans.constants2StoreJson(langedconstants)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(constantsJson,ensure_ascii=False)
    print "Constants",constants.deployId,finalJson
    cursor.execute(sql,(constants.deployId,ModelTypes.Type_Constants,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployForge_item_dataAction(request):
    try:
        cursor = connection.cursor()
        clearAllForge_item_datas(cursor)
        deployAllForge_item_datas(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllForge_item_datas_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Forge_item_data,))
    if count > 0 :
        ids = cursor.fetchall()
        for forge_item_dataId in ids :
            removeLanguage(cursor,forge_item_dataId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Forge_item_data,))

def clearAllForge_item_datas(cursor):
    sql = """ select deployId from mvc_forge_item_data """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllForge_item_datas(cursor):
    forge_item_datas = Forge_item_data.objects.all()
    for forge_item_data in forge_item_datas:
        gameId = deployForge_item_data(cursor,forge_item_data)
        

def deployForge_item_data(cursor,forge_item_data):
    langedforge_item_data = Forge_item_data()
    langedforge_item_data.id = forge_item_data.id
    langedforge_item_data.deployId = forge_item_data.deployId
    langednamex = 'forge_item_data'
    langedforge_item_data.count = forge_item_data.count
    langedforge_item_data.min = forge_item_data.min
    langedforge_item_data.max = forge_item_data.max
    langedforge_item_data.gold = forge_item_data.gold
    
    forge_item_dataJson = trans.forge_item_data2StoreJson(langedforge_item_data)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(forge_item_dataJson,ensure_ascii=False)
    print "Forge_item_data",forge_item_data.deployId,finalJson
    cursor.execute(sql,(forge_item_data.deployId,ModelTypes.Type_Forge_item_data,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployItem_fragmentAction(request):
    try:
        cursor = connection.cursor()
        clearAllItem_fragments(cursor)
        deployAllItem_fragments(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllItem_fragments_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Item_fragment,))
    if count > 0 :
        ids = cursor.fetchall()
        for item_fragmentId in ids :
            removeLanguage(cursor,item_fragmentId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Item_fragment,))

def clearAllItem_fragments(cursor):
    sql = """ select deployId from mvc_item_fragment """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllItem_fragments(cursor):
    item_fragments = Item_fragment.objects.all()
    for item_fragment in item_fragments:
        gameId = deployItem_fragment(cursor,item_fragment)
        

def deployItem_fragment(cursor,item_fragment):
    langeditem_fragment = Item_fragment()
    langeditem_fragment.id = item_fragment.id
    langeditem_fragment.deployId = item_fragment.deployId
    langednamex = 'item_fragment'
    langeditem_fragment.itemId = item_fragment.itemId
    langeditem_fragment.type = item_fragment.type
    langeditem_fragment.fragments = item_fragment.fragments
    
    item_fragmentJson = trans.item_fragment2StoreJson(langeditem_fragment)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(item_fragmentJson,ensure_ascii=False)
    print "Item_fragment",item_fragment.deployId,finalJson
    cursor.execute(sql,(item_fragment.deployId,ModelTypes.Type_Item_fragment,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployItem_extra_propAction(request):
    try:
        cursor = connection.cursor()
        clearAllItem_extra_props(cursor)
        deployAllItem_extra_props(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllItem_extra_props_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Item_extra_prop,))
    if count > 0 :
        ids = cursor.fetchall()
        for item_extra_propId in ids :
            removeLanguage(cursor,item_extra_propId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Item_extra_prop,))

def clearAllItem_extra_props(cursor):
    sql = """ select deployId from mvc_item_extra_prop """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllItem_extra_props(cursor):
    item_extra_props = Item_extra_prop.objects.all()
    for item_extra_prop in item_extra_props:
        gameId = deployItem_extra_prop(cursor,item_extra_prop)
        

def deployItem_extra_prop(cursor,item_extra_prop):
    langeditem_extra_prop = Item_extra_prop()
    langeditem_extra_prop.id = item_extra_prop.id
    langeditem_extra_prop.deployId = item_extra_prop.deployId
    langednamex = 'item_extra_prop'
    langeditem_extra_prop.level = item_extra_prop.level
    langeditem_extra_prop.property = item_extra_prop.property
    langeditem_extra_prop.valueType = item_extra_prop.valueType
    langeditem_extra_prop.min = item_extra_prop.min
    langeditem_extra_prop.max = item_extra_prop.max
    
    item_extra_propJson = trans.item_extra_prop2StoreJson(langeditem_extra_prop)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(item_extra_propJson,ensure_ascii=False)
    print "Item_extra_prop",item_extra_prop.deployId,finalJson
    cursor.execute(sql,(item_extra_prop.deployId,ModelTypes.Type_Item_extra_prop,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployItem_perfect_prop_dataAction(request):
    try:
        cursor = connection.cursor()
        clearAllItem_perfect_prop_datas(cursor)
        deployAllItem_perfect_prop_datas(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllItem_perfect_prop_datas_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Item_perfect_prop_data,))
    if count > 0 :
        ids = cursor.fetchall()
        for item_perfect_prop_dataId in ids :
            removeLanguage(cursor,item_perfect_prop_dataId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Item_perfect_prop_data,))

def clearAllItem_perfect_prop_datas(cursor):
    sql = """ select deployId from mvc_item_perfect_prop_data """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllItem_perfect_prop_datas(cursor):
    item_perfect_prop_datas = Item_perfect_prop_data.objects.all()
    for item_perfect_prop_data in item_perfect_prop_datas:
        gameId = deployItem_perfect_prop_data(cursor,item_perfect_prop_data)
        

def deployItem_perfect_prop_data(cursor,item_perfect_prop_data):
    langeditem_perfect_prop_data = Item_perfect_prop_data()
    langeditem_perfect_prop_data.id = item_perfect_prop_data.id
    langeditem_perfect_prop_data.deployId = item_perfect_prop_data.deployId
    langednamex = 'item_perfect_prop_data'
    langeditem_perfect_prop_data.itemQuality = item_perfect_prop_data.itemQuality
    langeditem_perfect_prop_data.type = item_perfect_prop_data.type
    langeditem_perfect_prop_data.prop = item_perfect_prop_data.prop
    langeditem_perfect_prop_data.min = item_perfect_prop_data.min
    langeditem_perfect_prop_data.max = item_perfect_prop_data.max
    
    item_perfect_prop_dataJson = trans.item_perfect_prop_data2StoreJson(langeditem_perfect_prop_data)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(item_perfect_prop_dataJson,ensure_ascii=False)
    print "Item_perfect_prop_data",item_perfect_prop_data.deployId,finalJson
    cursor.execute(sql,(item_perfect_prop_data.deployId,ModelTypes.Type_Item_perfect_prop_data,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployHomeAction(request):
    try:
        cursor = connection.cursor()
        clearAllHomes(cursor)
        deployAllHomes(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllHomes_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Home,))
    if count > 0 :
        ids = cursor.fetchall()
        for homeId in ids :
            removeLanguage(cursor,homeId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Home,))

def clearAllHomes(cursor):
    sql = """ select deployId from mvc_home """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllHomes(cursor):
    homes = Home.objects.all()
    for home in homes:
        gameId = deployHome(cursor,home)
        resources.deployResource(cursor,home.deployId,ModelTypes.Type_Home,home.homeres)
        

def deployHome(cursor,home):
    langedhome = Home()
    langedhome.id = home.id
    langedhome.deployId = home.deployId
    langednamex = 'home'
    langedhome.homeId = home.homeId
    langedhome.cellId = home.cellId
    langedhome.level = home.level
    langedhome.cardId = home.cardId
    langedhome.taskId = home.taskId
    langedhome.homeres = home.homeres
    
    homeJson = trans.home2StoreJson(langedhome)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(homeJson,ensure_ascii=False)
    print "Home",home.deployId,finalJson
    cursor.execute(sql,(home.deployId,ModelTypes.Type_Home,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployOpen_bagAction(request):
    try:
        cursor = connection.cursor()
        clearAllOpen_bags(cursor)
        deployAllOpen_bags(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllOpen_bags_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Open_bag,))
    if count > 0 :
        ids = cursor.fetchall()
        for open_bagId in ids :
            removeLanguage(cursor,open_bagId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Open_bag,))

def clearAllOpen_bags(cursor):
    sql = """ select deployId from mvc_open_bag """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllOpen_bags(cursor):
    open_bags = Open_bag.objects.all()
    for open_bag in open_bags:
        gameId = deployOpen_bag(cursor,open_bag)
        

def deployOpen_bag(cursor,open_bag):
    langedopen_bag = Open_bag()
    langedopen_bag.id = open_bag.id
    langedopen_bag.deployId = open_bag.deployId
    langednamex = 'open_bag'
    langedopen_bag.bagCount = open_bag.bagCount
    langedopen_bag.gold = open_bag.gold
    
    open_bagJson = trans.open_bag2StoreJson(langedopen_bag)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(open_bagJson,ensure_ascii=False)
    print "Open_bag",open_bag.deployId,finalJson
    cursor.execute(sql,(open_bag.deployId,ModelTypes.Type_Open_bag,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deploySilver_bagAction(request):
    try:
        cursor = connection.cursor()
        clearAllSilver_bags(cursor)
        deployAllSilver_bags(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllSilver_bags_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Silver_bag,))
    if count > 0 :
        ids = cursor.fetchall()
        for silver_bagId in ids :
            removeLanguage(cursor,silver_bagId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Silver_bag,))

def clearAllSilver_bags(cursor):
    sql = """ select deployId from mvc_silver_bag """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllSilver_bags(cursor):
    silver_bags = Silver_bag.objects.all()
    for silver_bag in silver_bags:
        gameId = deploySilver_bag(cursor,silver_bag)
        

def deploySilver_bag(cursor,silver_bag):
    langedsilver_bag = Silver_bag()
    langedsilver_bag.id = silver_bag.id
    langedsilver_bag.deployId = silver_bag.deployId
    langednamex = 'silver_bag'
    langedsilver_bag.itemId = silver_bag.itemId
    langedsilver_bag.silvers = silver_bag.silvers
    
    silver_bagJson = trans.silver_bag2StoreJson(langedsilver_bag)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(silver_bagJson,ensure_ascii=False)
    print "Silver_bag",silver_bag.deployId,finalJson
    cursor.execute(sql,(silver_bag.deployId,ModelTypes.Type_Silver_bag,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployGift_bagAction(request):
    try:
        cursor = connection.cursor()
        clearAllGift_bags(cursor)
        deployAllGift_bags(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllGift_bags_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Gift_bag,))
    if count > 0 :
        ids = cursor.fetchall()
        for gift_bagId in ids :
            removeLanguage(cursor,gift_bagId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Gift_bag,))

def clearAllGift_bags(cursor):
    sql = """ select deployId from mvc_gift_bag """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllGift_bags(cursor):
    gift_bags = Gift_bag.objects.all()
    for gift_bag in gift_bags:
        gameId = deployGift_bag(cursor,gift_bag)
        

def deployGift_bag(cursor,gift_bag):
    langedgift_bag = Gift_bag()
    langedgift_bag.id = gift_bag.id
    langedgift_bag.deployId = gift_bag.deployId
    langednamex = 'gift_bag'
    langedgift_bag.itemId = gift_bag.itemId
    langedgift_bag.reward = gift_bag.reward
    
    gift_bagJson = trans.gift_bag2StoreJson(langedgift_bag)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(gift_bagJson,ensure_ascii=False)
    print "Gift_bag",gift_bag.deployId,finalJson
    cursor.execute(sql,(gift_bag.deployId,ModelTypes.Type_Gift_bag,0,langednamex,0,finalJson,))
    return cursor.lastrowid



def deployTreasureAction(request):
    try:
        cursor = connection.cursor()
        clearAllTreasures(cursor)
        deployAllTreasures(cursor)
        transaction.commit()
        return HttpResponse(json.dumps({'code':1}),mimetype='application/json')
    except Exception,e:
        transaction.rollback()
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}),mimetype='application/json')

def clearAllTreasures_reserve(cursor):
    sql = """ select id from dic_game where `type` = %s """
    count = cursor.execute(sql,(ModelTypes.Type_Treasure,))
    if count > 0 :
        ids = cursor.fetchall()
        for treasureId in ids :
            removeLanguage(cursor,treasureId[0])
        sql = """ delete from dic_game where `type` = %s """
        cursor.execute(sql,(ModelTypes.Type_Treasure,))

def clearAllTreasures(cursor):
    sql = """ select deployId from mvc_treasure """
    cursor.execute(sql)
    deployIds = cursor.fetchall()
    for deployId in deployIds :
        removeLanguage(cursor,deployId[0])
        removeGameRecord(cursor,deployId[0])

def deployAllTreasures(cursor):
    treasures = Treasure.objects.all()
    for treasure in treasures:
        gameId = deployTreasure(cursor,treasure)
        

def deployTreasure(cursor,treasure):
    langedtreasure = Treasure()
    langedtreasure.id = treasure.id
    langedtreasure.deployId = treasure.deployId
    langednamex = 'treasure'
    langedtreasure.itemId = treasure.itemId
    langedtreasure.items = treasure.items
    
    treasureJson = trans.treasure2StoreJson(langedtreasure)
    sql = """insert into dic_game(`deploy_id`,`type`,`father_id`,`name`,`version`,`dict`) values(%s,%s,%s,%s,%s,%s)"""
    finalJson =  json.dumps(treasureJson,ensure_ascii=False)
    print "Treasure",treasure.deployId,finalJson
    cursor.execute(sql,(treasure.deployId,ModelTypes.Type_Treasure,0,langednamex,0,finalJson,))
    return cursor.lastrowid


def removeGameRecord(cursor,deployId):
    sql = """ delete from dic_game where `deploy_id` = %s """
    cursor.execute(sql,(deployId,))

def removeLanguage(cursor,gameId):
    sql = """ delete from dic_language where `deploy_id` = %s """
    cursor.execute(sql,(gameId,))

def deployLanguage(cursor,langId,gameId,deployId):
    lang = Language.objects.get(id=langId)
    sql = """insert into dic_language(`item_id`,`deploy_id`,`key`,`language`,`value`,`version`) values(%s,%s,%s,%s,%s,%s)"""
    cursor.execute(sql,(gameId,deployId,lang.key,'default',lang.value,1,));